package com.example.minaim;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.minaim.ClientHandler.Callback;
import com.example.minaim.Define.ClientStatus;
import com.example.minaim.MainActivity.MyReceiver;

public class RunActivity extends Activity {

	private String HPHead = "琛� ";
	private String MPHead = "姘� ";
	private String ATHead = "鏀� ";
	private String DEHead = "闃� ";
	private String VictoryHead = "鑳滃埄: ";
	private String FailedHead = "澶辫触: ";
	
	private Button  btnTianfu;
	private Button  btnSkill;
	private Button  btnBattle;
	private Button  btnfuben;
	private Button  btntafang;
	private Button  btnwulin;
	private Button  btnHelp;

	private Button  btnAddDE;
	private Button  btnAddHp;
	private Button  btnAddMp;
	private Button  btnOK;
	private Button  btnCancle;
	
	private Button btnPoint;
	
	private TextView textHp;
	private TextView textMP;
	private TextView textAT;
	private TextView textDE;
	
	private TextView textVictory;
	private TextView textFailed;
	
	private Define define;
	
	private MyReceiver receiver;
	
	private User userInfo;
	private HashMap<String, BaseSkill> baseskills;
	private List<BaseSkill> baseSkillsList;
	
	private HashMap<String, Skill> allSkills;	
	private List<Skill> allSkillsList;
	
	public ClientStatus clientStatus = ClientStatus.idle;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);//鍘绘帀鏍囬鏍�
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				  WindowManager.LayoutParams.FLAG_FULLSCREEN);//璁剧疆鍏ㄥ睆
		super.onCreate(savedInstanceState);
		setContentView(R.layout.run_main);
		
		btnTianfu = (Button) findViewById(R.id.btnTianfu);
		btnSkill = (Button) findViewById(R.id.btnSkill);
		btnBattle = (Button) findViewById(R.id.btnBattle);
		btnfuben = (Button) findViewById(R.id.btnfuben);
		btnHelp = (Button) findViewById(R.id.btnHelp);
		btnAddDE = (Button) findViewById(R.id.btnAddDE);
		btnAddHp = (Button) findViewById(R.id.btnAddHp);
		btnAddMp = (Button) findViewById(R.id.btnAddMp);
		btnOK = (Button) findViewById(R.id.btnOK);
		btnCancle = (Button) findViewById(R.id.btnCancle);
		btntafang = (Button) findViewById(R.id.btntafang);
		btnwulin = (Button) findViewById(R.id.btnwulin);
	
		
		btnPoint = (Button) findViewById(R.id.btnPoint);
		
		textHp = (TextView) findViewById(R.id.textHp);
		textMP = (TextView) findViewById(R.id.textMP);
		textAT = (TextView) findViewById(R.id.textAT);
		textDE = (TextView) findViewById(R.id.textDE);	
		textVictory = (TextView) findViewById(R.id.textVictory);	
		textFailed = (TextView) findViewById(R.id.textFailed);	
		
		baseskills = new HashMap<String,BaseSkill>();
		allSkills = new HashMap<String, Skill>();
		baseSkillsList = new ArrayList<BaseSkill>();
		allSkillsList = new ArrayList<Skill>();
		
		
		receiver = new MyReceiver();                
		IntentFilter filter = new IntentFilter();		
		filter.addAction("com.minam.test");		
		RunActivity.this.registerReceiver(receiver, filter);	
		
		userInfo = new User();
		
		new Thread( new Runnable() {     
		    public void run() {     
		        try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        clientStatus = ClientStatus.roleinfo;
		        
		        while(clientStatus != ClientStatus.idle)
		        {
		        	switch (clientStatus)
		        	{
						case roleinfo:
					        String GRoleInfoCmd="GROLEINFO:";				
							
							Intent intent = new Intent();	
							intent.putExtra("cmd","send");
							intent.putExtra("body",GRoleInfoCmd);
							intent.setAction("com.minam.client");// action涓庢帴鏀跺櫒鐩稿悓		
							sendBroadcast(intent);
							clientStatus = ClientStatus.roleinfoing;
							break;
						case baseskill:
							String baseskillCmd="GETBASESKILL:";				
							
							Intent intent1 = new Intent();	
							intent1.putExtra("cmd","send");
							intent1.putExtra("body",baseskillCmd);
							intent1.setAction("com.minam.client");// action涓庢帴鏀跺櫒鐩稿悓		
							sendBroadcast(intent1);
							clientStatus = ClientStatus.baseskilling;
							
							break;
						case allskills:
							String allskillsCmd="GETALLSKILLS:";				
							
							Intent intent2 = new Intent();	
							intent2.putExtra("cmd","send");
							intent2.putExtra("body",allskillsCmd);
							intent2.setAction("com.minam.client");// action涓庢帴鏀跺櫒鐩稿悓		
							sendBroadcast(intent2);
							clientStatus = ClientStatus.allskillsing;
							
							
							break;
							
						default:
							break;
					}

					try
					{
						Thread.sleep(100);
					} catch (InterruptedException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        }
		     }            
		}).start();
		
		
		btnTianfu.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				Intent tianfuIntent = new Intent(RunActivity.this, tianfuActivity.class);
				
				Bundle b = new Bundle();
				b.putSerializable("allbaseskills", baseskills);
				b.putSerializable("baseSkillsList", (Serializable) baseSkillsList);
				b.putString("baseskill", userInfo.get_baseskill());
				tianfuIntent.putExtras(b);
				
				startActivity(tianfuIntent);
			}
		});

		btntafang.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});
		btnwulin.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnSkill.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				Intent tianfuIntent = new Intent(RunActivity.this, skillsActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("allSkills", allSkills);
				b.putSerializable("allSkillsList", (Serializable) allSkillsList);
				b.putSerializable("userInfo", userInfo);
				tianfuIntent.putExtras(b);
				startActivity(tianfuIntent);
			}
		});

		btnBattle.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				Intent battleIntent = new Intent(RunActivity.this, battleActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("baseSkillsList", (Serializable) baseSkillsList);
				b.putSerializable("allSkillsList", (Serializable) allSkillsList);
				b.putSerializable("userInfo", userInfo);
				battleIntent.putExtras(b);
				startActivity(battleIntent);	
			}
		});

		btnfuben.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnHelp.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnAddDE.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnAddHp.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnAddMp.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnOK.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		btnCancle.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}
		});

		
	}
	
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            //当前为横屏， 在此处添加额外的处理代码
        }
        else if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            //当前为竖屏， 在此处添加额外的处理代码
        }
        //检测实体键盘的状态：推出或者合上
        if (newConfig.hardKeyboardHidden
                == Configuration.HARDKEYBOARDHIDDEN_NO){
            //实体键盘处于推出状态，在此处添加额外的处理代码
        }
        else if (newConfig.hardKeyboardHidden
                == Configuration.HARDKEYBOARDHIDDEN_YES){
            //实体键盘处于合上状态，在此处添加额外的处理代码
        }
    }
	
	
	public class MyReceiver extends BroadcastReceiver
    {
        
        // 鑷畾涔変竴涓箍鎾帴鏀跺櫒
        
        @Override
        public void onReceive(Context context, Intent intent)
        {
            
            // TODO Auto-generated method stub
            
            System.out.println("RunActivity OnReceiver");
            
            Bundle bundle = intent.getExtras();
            
            String cmd = bundle.getString("cmd");
            
            if (cmd.equals("receive")) {
            	String body = bundle.getString("body");
            	Cmd2vector cmd2vector = new Cmd2vector();
            	cmd2vector.cmd2vector(body);
            	//c06&name=liuyuhui&nickName=&baseskill=&de=5&hp=5&IsFirst=0&mp=5&NowFailed=0&NowVictory=0&sex=&skills=&st=5&sypoint=10&totalFailed=0&totalpoint=30&totalVictory=0
            	if (cmd2vector.cmd.equals("c06")) {
					//String result = cmd2vector.paras.get("f");
            		userInfo.set_baseskill(cmd2vector.paras.get("baseskill"));
            		userInfo.set_de(Integer.parseInt(cmd2vector.paras.get("de")));
            		userInfo.set_hp(Integer.parseInt(cmd2vector.paras.get("hp")));
            		userInfo.set_isfirst(Integer.parseInt(cmd2vector.paras.get("IsFirst")));
            		//userInfo.set_ispaiduser(cmd2vector.paras.get("baseskill"));
            		userInfo.set_mp(Integer.parseInt(cmd2vector.paras.get("mp")));
            		userInfo.set_name(cmd2vector.paras.get("name"));
            		userInfo.set_nickname(cmd2vector.paras.get("nickName"));
            		userInfo.set_nowfailed(Integer.parseInt(cmd2vector.paras.get("NowFailed")));
            		userInfo.set_nowvictory(Integer.parseInt(cmd2vector.paras.get("NowVictory")));
            		//userInfo.set_password(cmd2vector.paras.get("baseskill"));
            		userInfo.set_sex(cmd2vector.paras.get("sex"));
            		userInfo.set_skills(cmd2vector.paras.get("skills"));
            		userInfo.set_st(Integer.parseInt(cmd2vector.paras.get("st")));
            		userInfo.set_sypoint(Integer.parseInt(cmd2vector.paras.get("sypoint")));
            		userInfo.set_totalfailed(Integer.parseInt(cmd2vector.paras.get("totalFailed")));
            		userInfo.set_totalvictory(Integer.parseInt(cmd2vector.paras.get("totalVictory")));
            		
            		btnPoint.setText(Integer.toString(userInfo.get_sypoint()));
            		
            		//String temp = "琛� " + Integer.toString(userInfo.get_hp());
            		
            		textHp.setText(HPHead + Integer.toString(userInfo.get_hp()));
            		textMP.setText(MPHead + Integer.toString(userInfo.get_mp()));
            		textAT.setText(ATHead + Integer.toString(userInfo.get_st()));
            		textDE.setText(DEHead + Integer.toString(userInfo.get_de()));
            		
            		textVictory.setText(VictoryHead + Integer.toString(userInfo.get_totalvictory()));
            		textFailed.setText(FailedHead + Integer.toString(userInfo.get_totalfailed())); 
            		
            		clientStatus = ClientStatus.baseskill;
				}
            	
            	if (cmd2vector.cmd.equals("c05")) {
					//String result = cmd2vector.paras.get("f");
            		//c05&total=2&number=1&name=濮濓箒鈧懎銇夌挧?desc=閹碘偓閺堝鏁鹃崙缁樺Η閼宠姤鏁鹃崙璇插婢х偛濮�%

            		BaseSkill aBaseSkill = new BaseSkill();
            		aBaseSkill.set_name(cmd2vector.paras.get("name"));
            		aBaseSkill.set_desc(cmd2vector.paras.get("desc"));
            		baseskills.put(cmd2vector.paras.get("number"), aBaseSkill);
            		baseSkillsList.add(aBaseSkill);
            		
            		if (cmd2vector.paras.get("total").equals(cmd2vector.paras.get("number"))) {
						
            			clientStatus = ClientStatus.allskills;
					}  		
            		
				}
            	
            	if (cmd2vector.cmd.equals("c04")) {
					//String result = cmd2vector.paras.get("f");
            		//c05&total=2&number=1&name=9yin&curse_at=1&curse_de=1&damage=1
            		//&damage_hot=1&damage_hot_time=1&damage_poison=1&desc=9yin9yin9yin9yin婵傛垝绗㈢憲?
            		//hp_suck=1&mp=1&mp_suck=1
            		Skill aSkill = new Skill();
            		aSkill.set_name(cmd2vector.paras.get("name"));
            		aSkill.set_curse_at(Integer.parseInt(cmd2vector.paras.get("curse_at")));
            		aSkill.set_curse_de(Integer.parseInt(cmd2vector.paras.get("curse_de")));
            		aSkill.set_damage(Integer.parseInt(cmd2vector.paras.get("damage")));
            		aSkill.set_damage_hot(Integer.parseInt(cmd2vector.paras.get("damage_hot")));
            		aSkill.set_damage_hot_time(Integer.parseInt(cmd2vector.paras.get("damage_hot_time")));
            		aSkill.set_damage_poison(Integer.parseInt(cmd2vector.paras.get("damage_poison")));
            		aSkill.set_desc(cmd2vector.paras.get("desc"));
            		aSkill.set_hp_suck(Integer.parseInt(cmd2vector.paras.get("hp_suck")));
            		aSkill.set_mp(Integer.parseInt(cmd2vector.paras.get("mp")));
            		aSkill.set_mp_suck(Integer.parseInt(cmd2vector.paras.get("mp_suck")));
           		    allSkills.put(aSkill.get_name(), aSkill);
           		    allSkillsList.add(aSkill);
           		    
            		if (cmd2vector.paras.get("total").equals(cmd2vector.paras.get("number"))) {
            			clientStatus = ClientStatus.idle;
					}  		
            		
            		
				}
            	
            }

        }
        
        public MyReceiver()
        {
            
            System.out.println("MyReceiver");
            
            // 鏋勯�鍑芥暟锛屽仛涓�簺鍒濆鍖栧伐浣滐紝鏈緥涓棤浠讳綍浣滅敤
            
        }
        
    }
	
}
